package shaw.wifi.network;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.HttpParams;

import android.content.Context;

import com.byarger.exchangeit.EasySSLSocketFactory;

public class CertHttpClient extends DefaultHttpClient {
	/* This class is an extension of the DefaultHttpClient and will allow
	 * the application to connect via SSL to a server with a self-signed
	 * certificate, assuming that the application owns a copy of the certificate,
	 * which is located in the certificate store (res/raw/certstore.bks).
	 * If the certificate of the server would be recognized (ie. signed by a CA
	 * which is recognized by the phone) this is not required and the instances
	 * of CertHttpClient in the NetworkSettingsClient class could be replaced
	 * by DefaultHttpClients.
	 */
	
	//the context from which to load the store
	final Context context;

	public CertHttpClient(Context ctx, HttpParams httpParams) {
		//set http parameters (values for timeouts in this case)
		super(httpParams);
		
		//store the given context
		context = ctx;
	}
	
	@Override
	protected ClientConnectionManager createClientConnectionManager() {
		//define a secheme for http. Http will use a regular socket and connect on port 80
		//as expected
		Scheme httpScheme = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
		
		//define an https scheme, which will connect on port 443 and use an SSL socket
		//created by the SSLSocketFactory which permits the self signed certificate saved
		//in the store
		
		//the EasySSLSocketFactory allows for self signed certificates and
		//should be replaced if a valid certificate is available (it should be)
		Scheme httpsScheme = new Scheme("https", new EasySSLSocketFactory(), 443);
		
		//register these schemes with a registry
		SchemeRegistry sr = new SchemeRegistry();
		sr.register(httpScheme);
		sr.register(httpsScheme);
		
		//create the connection manager
		return new SingleClientConnManager(this.getParams(), sr);
	}
}
